package com.xxwy.study.server;

import com.xxwy.study.server.code.OrderFrameDecoder;
import com.xxwy.study.server.code.OrderFrameEncoder;
import com.xxwy.study.server.code.OrderProtocolDecoder;
import com.xxwy.study.server.code.OrderProtocolEncoder;
import com.xxwy.study.server.handler.OrderServerProcessHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.concurrent.ExecutionException;

/**
 * 服务端.
 *
 * @author xxwy
 * @date 2021/11/23 0023
 */
public class Server {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        serverBootstrap.group(eventExecutors)
                .channel(NioServerSocketChannel.class)
                .option(NioChannelOption.SO_BACKLOG, 1024)
                .childOption(NioChannelOption.TCP_NODELAY, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        pipeline.addLast(new OrderFrameDecoder());
                        pipeline.addLast(new OrderFrameEncoder());
                        pipeline.addLast(new OrderProtocolDecoder());
                        pipeline.addLast(new OrderProtocolEncoder());
                        pipeline.addLast(new OrderServerProcessHandler());
                    }
                });

        ChannelFuture channelFuture = serverBootstrap.bind(6666);
        channelFuture.channel().closeFuture().get();

    }

}
